<?php defined('SYSPATH') or die('No direct script access.');
/**
 * Default controller.
 */
class Product_Category_Controller extends Template_Controller 
{
	public function __construct()
	{
		parent::__construct();
		
		// Add the menu to the template
		$this->template->menu = new View('menu');
	}
	
	public function index()
	{	
		self::_rebuild_tree(1, 1, 0);
		self::lists(1);
	}
	
	public function lists($parent_id)
	{
		$parent_id = $parent_id == 0 ? 1 : $parent_id;
		
		$model = new Product_Category_Model();
		$category = $model->find_all_by_parent_id($parent_id);
		
		$parent = $model->find($parent_id);
		
		$table = new View('product/category_lists');
		$table->node_id = $parent_id;
		$table->node_parent_id = $parent->parent_id;
		$table->node_parent_name = $parent->name;
		$table->caption = 'Category List';
		$table->datas = $category;
		
		$this->template->content = $table->render();
	}
	
	public function create($parent_id)
	{
		$form = new Forge(NULL, 'New Category');
		$form->input('name')->label(TRUE);
		$form->input('title_cn')->label('Chinese Title')->rules('required');
		$form->input('title_en')->label('English Title')->rules('required');
		$form->submit('Save');
 
		if($form->validate())
		{
			//Load model and set values
			$category = new Product_Category_Model();
			$category->name = trim($form->name->value) == '' ? $form->title_cn->value : $form->name->value;
			$category->title_cn = $form->title_cn->value;
			$category->title_en = $form->title_en->value;
			$category->parent_id = $parent_id;
 
			//Save form into table
			if($category->save())
			{
				self::_rebuild_tree(1, 1, 0);
				url::redirect('product_category/lists/'.$parent_id);
			}
			else
			{
				echo 'no saving today';
			}
		}
		else
		{
		    $this->template->content = $form->html();
		}
	}
	
	public function edit($id)
	{
		$category = new Product_Category_Model($id);

		$form = new Forge(NULL, 'Edit Category');
		$form->input('name')->label(TRUE)->value($category->name);
		$form->input('title_cn')->label('Chinese Title')->rules('required')->value($category->title_cn);
		$form->input('title_en')->label('English Title')->rules('required')->value($category->title_en);
		$form->submit('Save');
 
		if($form->validate())
		{
			$category->name = $form->name->value;
			$category->title_cn = $form->title_cn->value;
			$category->title_en = $form->title_en->value;
 
			//Save form into table
			if($category->save())
			{
				url::redirect('product_category/lists/'.$category->parent_id);
			}
			else
			{
				echo 'no saving today';
			}
		}
		else
		{
		    $this->template->content = $form->html();
		}
	}
	
	public function delete($id)
	{
		$category = new Product_Category_Model($id);
		$parent_id = $category->parent_id;
		$category->delete();
		
		self::_rebuild_tree(1, 1, 0);

		url::redirect('product_category/lists/'.$parent_id);
	}
	
	public function product($category_id, $page_no)
	{
		$view = new View('product/category_product_lists');
		$view->category = new Product_Category_Model($category_id);
		
		$model = new Product_Model();
		
		$this->pagination = new Pagination(array(
	        'base_url'    => 'product_category/product/'.$category_id.'/', 
	        'uri_segment' => 4, 
			'items_per_page' => 10, 
	        'total_items' => $model->select('COUNT(*) AS records_found')
								   ->from('products AS p')
								   ->join('products_categories AS pc', 'p.id=pc.product_id')
								   ->where('pc.category_id', $category_id)->find()->records_found,
	    ));
	 
		$view->datas = $model->select('p.*')
						     ->from('products AS p')
						     ->join('products_categories AS pc', 'p.id=pc.product_id')
						     ->where('pc.category_id', $category_id)
						     ->limit(10, (($page_no - 1) * 10))->find_all();;
		
		$this->template->content = $view->render();
	}
	
	public function addproduct($category_id, $page_no)
	{
		//if(isset($_POST['selected_fld'])) print_r($_POST['selected_fld']);
		if(isset($_POST['selected_fld']))
		{
			$db = new Database();
			
			foreach($_POST['selected_fld'] as $product_id)
			{
				if($product_id != '')
					$db->insert('products_categories', array('category_id'=>$category_id, 'product_id'=>$product_id));
			}
			$db = null;
		}
		
		$view = new View('product/category_product_nolists');
		$view->category = new Product_Category_Model($category_id);
		$view->page_no = $page_no;
		
		$model = new Product_Model();
		
		$model->select('COUNT(*) AS records_found');
		
		if(isset($_GET['keyword']) and $_GET['keyword'] != '')
		{
			if($_GET['field'] == 'id')
				$model->where('id', (int)$_GET['keyword']);
			else
				$model->where($_GET['field']." like '%".$_GET['keyword']."%'");
		}
		
		$this->pagination = new Pagination(array(
	        'base_url'    => 'product_category/addproduct/'.$category_id.'/', 
	        'uri_segment' => 4, 
			'items_per_page' => 10, 
	        'total_items' => $model->where('id not in (select product_id from products_categories where category_id='.$category_id.')')->find()->records_found,
	    ));
		
		$model->select('*');
		
		if(isset($_GET['keyword']) and $_GET['keyword'] != '')
		{
			if($_GET['field'] == 'id')
				$model->where('id', (int)$_GET['keyword']);
			else
				$model->where($_GET['field']." like '%".$_GET['keyword']."%'");
		}
		
	 
		$view->datas = $model->where('id not in (select product_id from products_categories where category_id='.$category_id.')')
						     ->limit(10, (($page_no - 1) * 10))->find_all();;
		
		$this->template->content = $view->render();
	}
	
	public function moveproduct($category_id)
	{
		if(isset($_POST['selected_fld']))
		{
			$db = new Database();
			$db->query('DELETE FROM `products_categories` WHERE category_id='.$category_id.' AND product_id in ('.implode(",", $_POST['selected_fld']).')');
			$db = null;
		}
		
		url::redirect($_SERVER['HTTP_REFERER']);
	}
	
	protected function _rebuild_tree($parent_id, $left, $layer) 
	{   
		$db = new Database();
		
		// 这个节点的右值是左值加 1 
		$right = $left+1;   
		 
		// 获得这个节点的所有子节点 
		$result = $db->query('SELECT * FROM product_categories '.'WHERE parent_id='.$parent_id.' ORDER BY sort_order ASC, id ASC;'); 
		foreach ($result as $row) 
		{   
			// 对当前节点的每个子节点递归执行这个函数 
			// $right 是当前的右值，它会被 rebuild_tree 函数增加 
			$right = self::_rebuild_tree($row->id, $right, $layer+1);   
		} 
		 
		// 我们得到了左值，同时现在我们已经处理这个节点我们知道右值的子节点 
		$db->query('UPDATE product_categories SET left_id='.$left.', right_id='.$right.', layer_id='.$layer.' WHERE id='.$parent_id.';');  
		 
		// 返回该节点的右值+1 
		return $right+1;   
	}  
}